/**
微信公众平相关功能管理 Controller
@class company
@author :laiwp
@date:  :2016-05-04
@version : 0.1.0 
@constructor : 0.1.0 
*/

var config = require('../settings');
var log = require('../logger.js');
var crypto = require('crypto');
var tools = require('../tools.js');

var http = require('http');
var https = require('https');



module.exports = {
    mapping: {
        "_WxDataMenu": {
            "url": "/m/memu/wx",
            "method": "get",
            "description": "向微信公众平台进行菜单操作",
            "auth": false
        },
        "_WxMenuEditPage": {
            "url": "/wxpm/menu/index",
            "method": "get",
            "description": "向微信公众平台进行菜单操作",
            "auth": false
        },
        "_WxMenuEdit": {
            "url": "/wx/menu/edit",
            "method": "post",
            "description": "向微信公众平台进行菜单操作",
            "auth": false
        },
    },



    /**
    主页面.
    url:"/"
    请求方式:GET
    @method  _WxMenuEditPage
    @param req
    @param res
    @return 跳转到:/wxmp/weixinMenuEditView.html
    @private
    */
    _WxMenuEditPage: function(req, res) {

        console.log('33333---');
        res.render('./wxpm/weixinMenuEditView.html', {
            locals: {
                title: config.title,
                appid:config.appid,
                secret:config.secret,
            }
        });
    },

    /**
    向微信公众平台进行菜单操作.
    url:"/m/wx/menu/edit"
    请求方式:POST
    @method  _WxMenuEdit
    @param req
    @param res
    @return 
    @private
    */
    _WxMenuEdit: function(req, res) {

        var menu = req.param("menuBody");
        console.log('111---');
        var appid = req.param('appid');
        var secret = req.param('secret');
        //http%3a%2f%2fgo.sportscv.cn%2fsport%2flist

        var menu3 = '{' +
            '"button":[' +

            '{"name":"订场服务","type":"view", "name": "订场服务", "url": "https://open.weixin.qq.com/connect/oauth2/authorize?appid=' + config.appid + '&redirect_uri=http%3a%2f%2fgo.sportscv.cn&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect"},' +
            '{"name":"我的账户","type":"view", "name": "我的账户", "url": "https://open.weixin.qq.com/connect/oauth2/authorize?appid=' + config.appid + '&redirect_uri=http%3a%2f%2fgo.sportscv.cn%2f#myaccount&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect"}]}' +

            '{"type":"click","name":"b","key":"Ch02_CGAL"},' + //多余数据,保证数据长度正确

            ']' +

            '}';
            
        //取得access_token
        var tokenparam = "?grant_type=client_credential&appid="+appid+ "&secret=" +secret;
        console.log("=================================");
        console.log(tokenparam);
        var options = {
            hostname: 'api.weixin.qq.com',
            port: 443,
            path: '/cgi-bin/token' + tokenparam,
            //data: fqmenu1,
            method: 'GET',
            headers: {
                //'Content-Type': 'text/html',//'application/x-www-form-urlencoded',
                //'Content-Length': token.length + menus.length +6
                'Content-Length': tokenparam.length
            }
        };
        console.log('222---');
        var serareq = https.request(options, function(serares) {
            //log.logger.info('STATUS: ' + serares.statusCode);
            //log.logger.info('HEADERS: ' + JSON.stringify(serares.headers));
            serares.setEncoding('utf8');
            serares.on('data', function(respData) {
                var obj = eval("(" + respData + ")");
                console.log(obj.access_token);

                //统计有多少个汉字
                var gblen = countGb2312(menu3);

                if (req.param("menuType") == "创建菜单") {
                    var tmp = '/cgi-bin/menu/create' + token;
                    var len = tmp.length;
                    var token = "?access_token=" + obj.access_token;
                    var options = {
                        hostname: 'api.weixin.qq.com',
                        port: 443,
                        path: '/cgi-bin/menu/create' + token,
                        data: menu3,
                        method: 'POST',
                        headers: {
                            //'Content-Type': 'text/html',//'application/x-www-form-urlencoded',
                            'Content-Type': 'application/json; charset=UTF-8',
                            'Content-Length': menu3.length + gblen * 2
                        }
                    };
                    var serareq = https.request(options, function(serares) {
                        log.logger.info('STATUS: ' + serares.statusCode);
                        log.logger.info('HEADERS: ' + JSON.stringify(serares.headers));
                        serares.setEncoding('utf8');
                        serares.on('data', function(respData) {
                            console.log('rec Data=========================:\r\n' + respData);
                            //console.log('rec Data=========================:\r\n' + respData.errcode);
                            res.send(respData);
                        });
                    });
                    console.log('============' + menu3);
                    log.logger.info("Send menu packageData!!!!!!!!!!!!!!!!");
                    serareq.write(menu3);
                    serareq.end();
                } else if (req.param("menuType") == "菜单查询") {
                    console.log("菜单查询")
                    var token = "?access_token=" + obj.access_token;
                    var options = {
                        hostname: 'api.weixin.qq.com',
                        port: 443,
                        path: '/cgi-bin/menu/get' + token,
                        //data: menu,
                        method: 'GET',
                        headers: {
                            'Content-Type': 'text/html', //'application/x-www-form-urlencoded',
                            //'Content-Length': token.length + menus.length +6
                            //'Content-Length':  menu.length + len
                        }
                    };
                    var serareq = https.request(options, function(serares) {
                        log.logger.info('STATUS: ' + serares.statusCode);
                        log.logger.info('HEADERS: ' + JSON.stringify(serares.headers));
                        serares.setEncoding('utf8');
                        serares.on('data', function(respData) {
                            console.log('rec Data=========================:\r\n' + respData);
                            //console.log('rec Data=========================:\r\n' + respData.errcode);
                            res.send(respData);
                        });
                    });
                    console.log('============' + menu);
                    log.logger.info("Send menu packageData!!!!!!!!!!!!!!!!");
                    serareq.write(menu);
                    serareq.end();
                }

            });
        });
        log.logger.info("Send  token packageData!!!!!!!!!!!!!!!!");
        serareq.write(tokenparam);
        serareq.end();


    },   /**
     主页面.
     url:"/"
     请求方式:GET
     @method  WxIndex
     @param req
     @param res
     @return 跳转到:/mobile/wxindex.html
     @private
     */
    _WxIndex: function(req, res) {
        var signature = req.param("signature");
        var timestamp = req.param("timestamp");
        var nonce = req.param("nonce");
        var echostr = req.param("echostr");

        //记录日志到数据库
        var loginName = "",
            companyCode = "";
        try {
            loginName = req.session.userinfo.loginName;
            companyCode = req.session.userinfo.companyCode;
        } catch (ex) {};
        var logsInfo = {
            "name": "微信公众平台交易信息",
            "source": "weixinActivity->WxIndex",
            "level": "信息",
            "category": "交易信息", //错误信息
            "keywords": "微信公众平台",
            "channel": loginName,
            "computer": req.connection.remoteAddress,
            "eventData": "微信平台GET请求;/m/wx",
            "content": "signature=" + signature + ";timestamp=" + timestamp + ";nonce=" + nonce + ";echostr=" + echostr,
            "companyCode": companyCode,
        };

        //这里可以记录日志


        log.logger.info('Class:weixinController;Function:WxIndex;InfoMsg:微信平台返回参数:');
        log.logger.info('Class:weixinController;Function:WxIndex;InfoMsg:signature=' + signature);
        log.logger.info('Class:weixinController;Function:WxIndex;InfoMsg:timestamp=' + timestamp);
        log.logger.info('Class:weixinController;Function:WxIndex;InfoMsg:nonce=' + nonce);
        log.logger.info('Class:weixinController;Function:WxIndex;InfoMsg:echostr=' + echostr);
        res.send(echostr);

    },

};

//统计有多少个汉字
function countGb2312(str) {
    var count = 0;
    for (var i = 0; i < str.length; i++) {
        var code = str.charCodeAt(i);
        //console.log('countGb2312 code=' + code)
            //if(code >= 19968 && code <= 40869) {
        if (code >= 11968 && code <= 80869) {
            count++;
        }
    }
    return count;
}